import { MENU_TYPE_ENUM } from '../constants/menu-const';
import _ from 'lodash';

/** 调整菜单层级 **/
export const setChildMenu = (menu, menuList) => {
    const childMenuList = [];
    menuList.forEach((item) => {
        if (item.parentId === menu.id && item.displayFlag) {
            item.label = item.name;
            item.value = item.id;
            item.path = item.url;
            item.parent = JSON.parse(JSON.stringify(menu));
            childMenuList.push(item);
        }
    });

    childMenuList.sort((a, b) => a.sort - b.sort);
    menu.children = childMenuList;

    if (menu.children.length > 0) {
        menu.children.forEach((childMenu) => {
            setChildMenu(childMenu, menuList);
        });
    }
};

/** 调整角色菜单层级 **/
export const setChildRoleMenu = (roleMenu, roleMenuList) => {
    const childRoleMenuList = [];
    roleMenuList.forEach((item) => {
        if (item.parentId === roleMenu.menuId) {
            childRoleMenuList.push(item);
        }
    });

    roleMenu.children = childRoleMenuList;

    if (roleMenu.children.length > 0) {
        roleMenu.children.forEach((childRoleMenu) => {
            setChildRoleMenu(childRoleMenu, roleMenuList);
        });
    }
};

/**
 * 构建菜单父级集合
 */
export const buildMenuParentIdListMap = (menuTree) => {
    let menuParentIdListMap = new Map();
    recursiveBuildMenuParentIdListMap(menuTree, [], menuParentIdListMap);
    return menuParentIdListMap;
}

export const recursiveBuildMenuParentIdListMap = (menuList, parentMenuList, menuParentIdListMap) => {
    for (const e of menuList) {
        // 顶级parentMenuList清空
        if (e.parentId === 0) {
            parentMenuList = [];
        }
        let menuIdStr = (e.menuId || "").toString();
        let cloneParentMenuList = _.cloneDeep(parentMenuList);
        if (!_.isEmpty(e.children) && e.menuName) {
            // 递归
            cloneParentMenuList.push({ name: menuIdStr, title: e.menuName });
            recursiveBuildMenuParentIdListMap(e.children, cloneParentMenuList, menuParentIdListMap);
        } else {
            menuParentIdListMap.set(menuIdStr, cloneParentMenuList);
        }
    }
}

/**
 * 构建菜单树
 *
 * @param  menuList
 * @returns
 */
export const buildMenuTree = (menuList) => {
    //1 获取所有 有效的 目录和菜单
    let catalogAndMenuList = menuList.filter((menu) => !menu.disabledFlag);

    //2 获取顶级目录
    let topCatalogList = catalogAndMenuList.filter((menu) => menu.parentId === 0);
    for (const topCatalog of topCatalogList) {
        buildMenuChildren(topCatalog, catalogAndMenuList);
    }
    return topCatalogList;
}

export const buildMenuChildren = (menu, allMenuList) => {
    let children = allMenuList.filter((e) => e.parentId === menu.menuId);
    if (children.length === 0) {
        return;
    }
    menu.children = children;
    for (const item of children) {
        buildMenuChildren(item, allMenuList);
    }
}

